#include <iostream>
using namespace std;
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int pipefd[2];
    // 1. 创建匿名管道
    int n = pipe(pipefd);
    if (n < 0)
    {
        cerr << "pipe failed ..." << "errno:" << errno << "strerror:" << strerror(errno) << endl;
        return 1;
    }
    // 2. 创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        // child
        close(pipefd[0]); // 关闭读端
        const char *msg = "father hello , I am your child...";
        int count = 10;
        while (count--)
        {
            ssize_t n = write(pipefd[1], msg, strlen(msg));
            if (n < 0)
            {
                cerr << "write failed ..." << "errno:" << errno << "strerror:" << strerror(errno) << endl;
                exit(2);
            }
            sleep(1);
        }
        close(pipefd[1]); // 关闭写端
        exit(0);
    }
    // father
    close(pipefd[1]);
    char buffer[1024];
    while (true)
    {
        ssize_t n = read(pipefd[0], buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = '\0';
            cout << "child send to father:" << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "read file end.." << endl;
            break;
        }
        else
        {
            cerr << "read failed ..." << "errno:" << errno << "strerror:" << strerror(errno) << endl;
            break;
        }
    }
    close(pipefd[0]);
    waitpid(id, nullptr, 0);
    return 0;
}